import json
import requests
# from tabulate import tabulate
#from typing import List, Dict

from openpyxl import Workbook
# from bs4 import BeautifulSoup
class ReadFile():
    @classmethod
    def read_cases(cls,file):
        '''
        @read_cases #用来读json用例文件
        :param file: 文件
        :return: 返回需要的数据
        '''
        with open(file, 'r', encoding='utf-8') as f:
            data = json.load(f)
            lst = []
            for i in data:
                lst.append(tuple(i.values()))
                # print(tuple(i.values()))
            return   lst
    @classmethod
    def read_data(cls,file):
        """
        :param file:
        :return: 区分元组，正常读取
        """
        with open(file, 'r', encoding='utf-8') as f:
            data = json.load(f)
            return   data
    @classmethod
    def get_swagger_info(cls,url):
        """
        @get_swagger_info 从 Swagger 文档中获取所有接口信息
        :param url: Swagger 文档地址
        :return: 所有接口信息列表
        """
        # 发送 GET 请求，获取 Swagger 文档
        response = requests.get(url)
        swagger_dict = response.json()
        # 获取所有 API 接口
        paths = swagger_dict.get('paths')
        basePath = swagger_dict.get("basePath")
        api_list = []
        # 遍历所有 API 接口
        for path, methods in paths.items():
            for method, info in methods.items():
                # 提取接口信息
                summary = info.get('summary', '')
                description = info.get('description', '')
                tags = info.get('tags', [])
                parameters = info.get('parameters', [])
                responses = info.get('responses', {})
                parameters_info = []
                for param_info in parameters:
                    name = param_info['name']
                    in_ = param_info['in']
                    required = param_info.get('required', False)
                    parameters_info.append({'name': name, 'in': in_, 'required': required})
                api_info = {
                    'path': basePath+path,
                    'method': method.lower(),
                    'summary': summary,
                    'description': description,
                    'parameters': parameters_info,
                    'responses': responses,
                    'tags': tags[0]
                }
                api_list.append(api_info)
        return api_list
# def visualize_swagger_info(api_list: List[Dict]):
#     """
#     可视化显示 Swagger 接口信息
#     :param api_list: 接口信息列表
#     """
#     headers = ['Path', 'Method', 'Summary', 'Description']
#     rows = []
#     for api in api_list:
#         row = [api['path'], api['method'], api['summary'], api['description']]
#         rows.append(row)
#     print(tabulate(rows, headers=headers, tablefmt="grid"))
#
#     for api in api_list:
#         print('Path:', api['path'])
#         print('Method:', api['method'])
#         print('Summary:', api['summary'])
#         print('Description:', api['description'])
#         print('Parameters:')
#         headers = ['Name', 'In', 'Required']
#         rows = []
#         for param in api['parameters']:
#             row = [param['name'], param['in'], param['required']]
#             rows.append(row)
#         print(tabulate(rows, headers=headers, tablefmt="grid"))
#         print('Responses:')
#         headers = ['Status Code', 'Description']
#         rows = []
#         for status_code, response in api['responses'].items():
#             description = response.get('description', '')
#             row = [status_code, description]
#             rows.append(row)
#         print(tabulate(rows, headers=headers, tablefmt="grid"))
#         print('\n')


    def save_swagger_info(self,url: str,filename: str):
        """
        @save_swagger_info #将 Swagger 接口信息保存为 JSON 文件
        :param url: 接口信息列表
        :param filename: 保存文件名
        """
        api_list = ReadFile.get_swagger_info(url)
        with open(filename, 'w') as f:
            json.dump(api_list, f, ensure_ascii=False, indent=4)
        print("成功保存 Swagger 接口信息到文件：", filename)


    def save_swagger_info_to_excel(self, url: str, sheet_name: str):
        """
        @save_swagger_info_to_excel 将 Swagger 接口信息从 JSON 文件中读取并保存至 Excel 文件
        :param url: Swagger 接口信息 JSON 文件名
        :param sheet_name: 要保存的工作表(sheet)名称
        """
        # 读取 Swagger 接口信息 JSON 文件
        filename = ReadFile.get_swagger_info(url=url)
        filename = str(filename)
        with open(filename, 'r') as f:
            api_list = json.load(f)

        wb = Workbook()
        ws = wb.active
        ws.title = sheet_name

        # 设置表头
        headers = ['Path', 'Method', 'Summary', 'Description', 'Tags', 'Parameters', 'Response']
        for col_num, header in enumerate(headers, 1):
            cell = ws.cell(row=1, column=col_num)
            cell.value = header

        # 填充数据
        for row_num, api in enumerate(api_list, 2):
            row = [api['path'], api['method'], api['summary'], api['description'], api['tags'], api['parameters'], api['responses']]
            for col_num, cell_value in enumerate(row, 1):
                cell = ws.cell(row=row_num, column=col_num)
                cell.value = str(cell_value)

        # 保存 Excel 文件
        wb.save(filename.replace('.json', '.xlsx'))
        print("成功保存 Swagger 接口信息到 Excel 工作簿：", filename.replace('.json', '.xlsx'))

if __name__ == '__main__':
    # r=read_data("../login.json")
    # print(r)
    url = "http://192.168.1.34:8081/authoritycontrolplatformapi/v2/api-docs?group=com.lztech.site.api.controller"
    ReadFile.get_swagger_info(url)


